package com.emm.yixun.website.controller.marketing;

//框架包

import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.common.model.SellControl;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.RetainDetailView;
import com.emm.yixun.common.model.dto.SellControlDto;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.marketing.service.RetainServiceFacade;
import com.emm.yixun.marketing.service.SellControlServiceFacade;
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.service.marketing.SellControlService;
import com.emm.yixun.website.utils.ExcelUtil;
import com.emm.yixun.website.vo.common.ExtResultVo;
//common
//website
//变化的引用

@Controller
@RequestMapping("/marketing/sellControl/")
public class SellControlController extends BaseController<SellControl> {

	@Autowired
	private SellControlServiceFacade sellControlServiceFacade;
	@Autowired
	private SellControlService controlService;
	@Autowired
	private RetainServiceFacade retainServiceFacade;

	@RequestMapping(value = "index")
	public String index(ModelMap map) {
		if (doSecurityIntercept(Const.RESOURCES_TYPE_MENU)) {
			// 查询菜单按钮权限
			map.put("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));
			return "/marketing/sellControl/list";
		}
		return Const.NO_AUTHORIZED_URL;
	}

	/**
	 * 方法描述 : 房源销控 创建者：ThinkPad 项目名称： emm-website 类名： SellControlController.java 版本： v1.0 创建时间： 2016年7月6日 上午10:53:21
	 * 
	 * @param roomId
	 * @return ModelAndView
	 */
	@RequestMapping(value = "addSellControlView")
	public ModelAndView addSellControlView(Long roomId,String jumpFlag) {
		return new ModelAndView("/marketing/sellControl/add").addObject("roomId", roomId).addObject("userName",
				ShiroUtil.getCurrentUser().getUserName()).addObject("jumpFlag",jumpFlag);
	}

	// 新增返回实体对象
	@RequestMapping(value = "add")
	@ResponseBody
	public AjaxRes add(SellControlDto dto, String starttime, String endTime) {
		AjaxRes ar = getAjaxRes();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		/*
		 * 1.判断权限2.调用新增接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:sellControl:add"))) {
			try {
				if (!StringUtils.isEmpty(starttime)) {
					dto.setStartValidity(df.parse(starttime));
				}
				if (!StringUtils.isEmpty(endTime)) {
					dto.setEndValidity(df.parse(endTime));
				}
				Response<SellControlDto> response = sellControlServiceFacade.save(dto, ShiroUtil.getCurrentUser());
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.SAVE_SUCCEED);
				} else {
					ar.setFailMsg(Const.SAVE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
		}
		return ar;
	}

	// 查看
	@RequestMapping(value = "view", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes view(Long id) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:sellControl:view"))) {
			try {
				Response<SellControl> response = sellControlServiceFacade.findById(id);
				if (response.isSuccess()) {
					ar.setSucceed(response.getEntity());
				} else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
		}
		return ar;
	}

	// 修改
	@RequestMapping(value = "edit", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes edit(SellControlDto dto) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用修改接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:sellControl:edit"))) {
			try {
				Response<Integer> response = sellControlServiceFacade.updateByPrimaryKey(dto, true);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.UPDATE_SUCCEED);
				} else {
					ar.setFailMsg(Const.UPDATE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
		}
		return ar;
	}

	// 删除
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes delete(Long id) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:sellControl:delete"))) {
			try {
				Response<Integer> response = sellControlServiceFacade.deleteByPrimaryKey(id);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.DEL_SUCCEED);
				} else {
					ar.setFailMsg(Const.DEL_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DEL_FAIL);
			}
		}
		return ar;
	}

	// 分页查询
	@RequestMapping(value = "list", method = RequestMethod.POST)
	@ResponseBody
	public Page<SellControlDto> list(SellControlDto dto, Integer limit, Integer page) {
		/*
		 * 1.判断权限2.调用分页查询接口3.返回信息
		 */
		if (doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:sellControl:list")) {
			try {
				dto=setSellQuery(dto);
				Response<Page<SellControlDto>> response = controlService.findPageByDto(dto, limit, page);
				if (response.isSuccess()) {
					Page<SellControlDto> pages = response.getEntity();
					pages.setPageNumber(page);
					return pages;
				} else {
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
			}
		}
		return new Page<SellControlDto>();
	}
	
	@RequestMapping(value = "sellExport")
	public void sellExport(String value,HttpServletResponse response,HttpServletRequest request){
		AjaxRes ar=getAjaxRes();
		try {
			if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:sell:export"))){
				String jsonStr=URLDecoder.decode(value,"utf-8");
				SellControlDto dto = JSONObject.parseObject(jsonStr, SellControlDto.class);
				dto=setSellQuery(dto);
				String[] name = new String[]{"销控信息"}; //sheet信息
				List<String[]> headerList = new ArrayList<String[]>(); //表头集合
				List<List<Map<String, String>>> list = new ArrayList<List<Map<String, String>>>(); //数据集合
				//设置表头字段
				String[] header = new String[]{
					"销控日期","房号","户型","房屋总价","销控有效开始日期","销控有效结束日期","经纪人","业务状态"
				};
				headerList.add(header);
				List<SellControlDto> sellList = controlService.querySellListExport(dto);
				List<Map<String, String>> listMap = controlService.returnFieldSell(sellList, header);
				list.add(listMap);
				ExcelUtil.exportExcel(list, headerList, name, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public SellControlDto setSellQuery(SellControlDto dto){
		if(dto.getControlDateAfter()!=null&&!dto.getControlDateAfter().equals("")){
			dto.setControlDateAfter(dto.getControlDateAfter()+" 23:59:59");
		}
		if(dto.getEndValidityAfter()!=null&&!dto.getEndValidityAfter().equals("")){
			dto.setEndValidityAfter(dto.getEndValidityAfter()+" 23:59:59");
		}
		dto.setOrders(" t.create_time desc ");
		User user = ShiroUtil.getCurrentUser();
		dto.setMerchantId(user.getMerchantId());
		dto.setPermissionUserId(user.getId());
		
		//项目数据权限资源缓存
		String resourcesCode = ShiroUtil.getDataPermissionResources(dto.getResourcesName());
		if(null == dto.getResourcesCode() || "".equals(dto.getResourcesCode())){
			dto.setResourcesCode(resourcesCode);
		}else if("".equals(resourcesCode)){
			ShiroUtil.setDataPermissionResources(dto.getResourcesName(), dto.getResourcesCode());
		}
		return dto;
	}

	@RequestMapping(value = "getprojectRoom")
	public @ResponseBody
	ExtResultVo getprojectRoom(Long id) {
		ExtResultVo vo = new ExtResultVo();
		RetainDetailView detail = retainServiceFacade.getProjectRoomInfo(new RetainDetailView(), id);
		vo.setData(detail);
		vo.setSuccess(true);
		return vo;
	}

	@RequestMapping(value = "sellDetail")
	public ModelAndView sellDetail(Long id,HttpServletRequest request,String returnUrl,String controlType) {
		Response<SellControl> sellcontrolResponse=sellControlServiceFacade.findById(id);
		if(sellcontrolResponse.isSuccess() && null!=sellcontrolResponse.getEntity()){
			SellControl sellControl=sellcontrolResponse.getEntity();
			controlType=sellControl.getControlType();
			
			Date startValidity=sellControl.getStartValidity();
			Date endValidity=sellControl.getEndValidity();
			//需要加一天
			endValidity=DateUtils.addDay(endValidity, 1);
			Date now=new Date();
			if(now.getTime()<startValidity.getTime() || now.getTime()>endValidity.getTime()){
				//当前时间不在销控时间内则撤销销控按钮不显示
				controlType="1";
			}
		}
		return new ModelAndView("/marketing/sellControl/sellDetail")
		.addObject("id", id)
		.addObject("permitBtn", getPermissionBtnArray())
		.addObject("menu", request.getParameter("menu"))
		.addObject("controlType", controlType)
		.addObject("returnUrl", returnUrl!=null&&!returnUrl.equals("")?returnUrl.replace(",", "/").replace("(", "?").replace(")", "="):"");
	}

	@RequestMapping(value = "resultSellDetail")
	public @ResponseBody
	ExtResultVo getSellDetail(Long id) {
		ExtResultVo view = new ExtResultVo();
		view.setSuccess(true);
		view.setData(sellControlServiceFacade.getSellDetail(id));
		return view;
	}

	@RequestMapping(value = "sellControlRevoke")
	public @ResponseBody
	AjaxRes sellControlRevoke(Long id, String remark) {
		AjaxRes ar = getAjaxRes();
		User user = ShiroUtil.getCurrentUser();
		Response<Boolean> result = sellControlServiceFacade.sellControlRevoke(id, user, remark);
		if (result.getEntity()) {
			ar.setSucceedMsg("撤销成功!");
		}
		return ar;
	}
	
	@RequestMapping(value = "batchSellControlRevoke")
	public @ResponseBody
	AjaxRes batchSellControlRevoke(String ids, String remark) {
		AjaxRes ar = getAjaxRes();
		User user = ShiroUtil.getCurrentUser();
		Response<Boolean> result = sellControlServiceFacade.batchSellControlRevoke(ids, user, remark);
		if (result.getEntity()) {
			ar.setSucceedMsg("撤销成功!");
		}
		return ar;
	}
}
